package com.ptt.sqm.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.ptt.sqm.component.Search;
import com.ptt.sqm.component.SpinnerObject;
import com.ptt.sqm.model.AssessItem;
import com.ptt.sqm.model.AssessItemChoice5018;
import com.ptt.sqm.model.AssessItemChoice5018List;
import com.ptt.sqm.model.AssessItemList;
import com.ptt.sqm.model.AssessItemPoint;
import com.ptt.sqm.model.AssessSubject5019;
import com.ptt.sqm.model.AssessSubject5019List;
import com.ptt.sqm.model.AssessSuggestion5034;
import com.ptt.sqm.model.AssessTran;
import com.ptt.sqm.model.AssessTranList;
import com.ptt.sqm.model.CycleAssess;
import com.ptt.sqm.model.Login;
import com.ptt.sqm.model.MakeAssess;
import com.ptt.sqm.model.MakeAssessList;
import com.ptt.sqm.model.SaveDraftAssessTranResult;
import com.ptt.sqm.model.SuggestionImage;
import com.ptt.sqm.model.SummaryAssess;
import com.ptt.sqm.session.SavedAssessTran;
import com.ptt.sqm.session.SavedItemAssess;
import com.ptt.sqm.session.SavedSummaryAssess;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.util.WebserviceUtil;
import com.ptt.sqm.util.WidgetUtil;
import com.ptt.sqm.ws.AsyncResponse;
import com.ptt.sqm.ws.DecrementCallback;
import com.ptt.sqm.ws.DefaultTask;
import com.ptt.sqm.ws.GeocoderJSONCall;
import com.ptt.sqm.ws.UploadCall;
import com.ptt.sqmonmobile.R;

public class MakeAssessFragment extends DefaultFragment implements AsyncResponse, DecrementCallback {

	// Saved Item Assess on pref
	private SavedItemAssess saveItemPref;

	private SavedSummaryAssess saveSummaryPref;

	// Create Webservice class object
	private DefaultTask mTask = null;

	private UploadCall uploadCall = null;

	private static MakeAssessFragment fragment;

	private MakeAssessList makeAssessList;

	private AssessItemList items;

	private Map<String, List<AssessItem>> itemMap = new TreeMap<String, List<AssessItem>>();

	private List<String> subjectKeys = new ArrayList<String>();

	private Map<String, String> itemRows = new TreeMap<String, String>();

	private Map<String, SummaryAssess> summaryAssess = new TreeMap<String, SummaryAssess>();

	private int numSubject;

	private int curSubject;

	private GoogleMap map;

	private boolean isCurrentFirst;

	private String projCycleStationId;

	private String latLng;

	private Search search;

	private View mProgressView;

	private View mContentView;

	// Save AssessTran
	private AssessTran saveAssessTran;

	private SavedAssessTran savedTranPref;

	private boolean isDraft;

	private boolean isSubmit;

	private int cnt;
	
	private boolean canBack;

	// For set AssessTran (SubjectName, ItemName)
	Map<String, String> subjectMap = new TreeMap<String, String>();
	Map<String, String> itemChoiceMap = new TreeMap<String, String>();

	private Login login;

	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static MakeAssessFragment newInstance(int sectionNumber, AssessItemList items, boolean isDraft) {
		fragment = new MakeAssessFragment(items, isDraft);
		Bundle args = new Bundle();
		args.putInt(AppUtil.ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);

		return fragment;
	}

	public static MakeAssessFragment newInstance(int sectionNumber, AssessItemList items, boolean isDraft, int curSubject) {
		fragment = new MakeAssessFragment(items, isDraft, curSubject);
		Bundle args = new Bundle();
		args.putInt(AppUtil.ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);

		return fragment;
	}

	public MakeAssessFragment(AssessItemList items, boolean isDraft) {
		// TODO Auto-generated constructor stub
		this.items = items;
		this.isDraft = isDraft;
	}

	public MakeAssessFragment(AssessItemList items, boolean isDraft, int curSubject) {
		// TODO Auto-generated constructor stub
		this.items = items;
		this.isDraft = isDraft;
		this.curSubject = curSubject;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		login = session.getUserDetails();

		// handle Back Pressed
		handleBackPressed();		
		
		// Loading...
		mProgressView = view.findViewById(R.id.progress);
		mContentView = view.findViewById(R.id.container);

		// Search Sliding
		final SlidingDrawer slide = (SlidingDrawer) view.findViewById(R.id.search_slider);

		final ViewGroup grid = (ViewGroup) slide.findViewById(R.id.content);

		// Top-to-bottom
		grid.setRotation(180);
		grid.setVisibility(LinearLayout.VISIBLE);
		slide.setRotation(180);

		// Search Input
		search = Search.getInstance(getActivity(), getView(), gson, com);
		search.showSearchForMake(getActivity(), getView());

		Button searchBtn = (Button) view.findViewById(R.id.seach_btn);
		Button clearBtn = (Button) view.findViewById(R.id.clear_btn);
		searchBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
				mNoData.setVisibility(TextView.VISIBLE);
				ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
				mHasData.setVisibility(ViewGroup.GONE);

				if (!login.isAdmin()) {
					if (WidgetUtil.isLocationServiceAvailable(getActivity())) {

						if (isValid()) {
							Spinner yearSpin = (Spinner) getView().findViewById(R.id.year_assess);
							Spinner projSpin = (Spinner) getView().findViewById(R.id.project_assess);
							Spinner cycleSpin = (Spinner) getView().findViewById(R.id.cycle_assess);

							String projectId = "", cycleAssessId = "", station = "", yearAssessId = "";
							search.assessItemList = new AssessItemList();

							if (yearSpin.getSelectedItemPosition() != 0) {
								yearAssessId = ((SpinnerObject) yearSpin.getSelectedItem()).getValue();
								search.assessItemList.yearAssessId = yearAssessId;
							}
							if (cycleSpin.getSelectedItemPosition() != 0) {
								cycleAssessId = ((SpinnerObject) cycleSpin.getSelectedItem()).getValue();
								search.assessItemList.cycleAssessId = cycleAssessId;
								search.assessItemList.cycle = ((SpinnerObject) cycleSpin.getSelectedItem()).getName();
							}
							if (projSpin.getSelectedItemPosition() != 0) {
								projectId = ((SpinnerObject) projSpin.getSelectedItem()).getValue();
								search.assessItemList.projectId = projectId;
								search.assessItemList.projectName = ((SpinnerObject) projSpin.getSelectedItem()).getName();
							}

							search.assessItemList.stationId = search.shipToSelected;
							search.assessItemList.stationName = search.shipNameSelected;
							search.assessItemList.locationId = search.locationSelected;

							slide.close();
							canBack = false;
							WidgetUtil.showProgress(mContentView, mProgressView, true);

							getAssessItemService(projectId, cycleAssessId);
							return;
						}
					}
				} else {
					Toast.makeText(getActivity(), AppUtil.toStringWithParam(getString(R.string.alert_permission_denied_for_assess), login.User_Group_Name), Toast.LENGTH_SHORT).show();
				}
			}
		});

		clearBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				clearSearchAssess();
			}
		});

		final ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
		TextView mNoData = (TextView) getView().findViewById(R.id.no_data);

		if (items != null) {
			canBack = false;
			WidgetUtil.showProgress(mContentView, mProgressView, true);

			// Location Services
			getLocationService();

			// Set AssessTran (SubjectName, ItemName)
			setSubjectAndItemName();

			projCycleStationId = items.projectId + AppUtil.UNDER_SCROLL + items.cycleAssessId + AppUtil.UNDER_SCROLL + items.stationId + AppUtil.UNDER_SCROLL + login.User_Group_Code;
			Log.i("step id", projCycleStationId);

			saveItemPref = new SavedItemAssess(getActivity().getApplicationContext());
			itemRows = saveItemPref.loadMap(projCycleStationId);
			saveSummaryPref = new SavedSummaryAssess(getActivity().getApplicationContext());
			summaryAssess = saveSummaryPref.loadMap(projCycleStationId);

			// Show Header
			((TextView) getView().findViewById(R.id.station_value)).setText(items.stationId + AppUtil.SPACE + items.stationName);
			((TextView) getView().findViewById(R.id.project_assess_value)).setText(items.projectName);
			((TextView) getView().findViewById(R.id.cycle_assess_value)).setText(items.cycle);
			((TextView) getView().findViewById(R.id.pbl)).setText(items.locationId);
			if (!login.isAdmin()) {
				((TextView) getView().findViewById(R.id.fullname_assess_value)).setText(login.User_Name);
				((TextView) getView().findViewById(R.id.group_assess_value)).setText(login.User_Group_Name);
			}

			// Get AssessTran
			saveAssessTranStep1_isDraft();

			slide.open();
			slide.close();
		} else {

			mNoData.setVisibility(TextView.INVISIBLE);
			mHasData.setVisibility(ViewGroup.GONE);
			slide.open();
		}
		// ////////////////////////////////////////////////
		if (slide.isOpened()) {
			ImageView handle = (ImageView) slide.findViewById(R.id.handle);
			handle.setImageResource(R.drawable.show);
			WidgetUtil.setupSlideOpened(getActivity(), mNoData, slide);
		}

		slide.setOnDrawerCloseListener(new OnDrawerCloseListener() {

			@Override
			public void onDrawerClosed() {
				// TODO Auto-generated method stub
				grid.setVisibility(LinearLayout.INVISIBLE);
				ImageView handle = (ImageView) slide.findViewById(R.id.handle);
				handle.setImageResource(R.drawable.hide);

				WidgetUtil.setupSlideClosed(getActivity(), mHasData);
			}
		});

		slide.setOnDrawerOpenListener(new OnDrawerOpenListener() {

			@Override
			public void onDrawerOpened() {
				// TODO Auto-generated method stub
				ImageView handle = (ImageView) slide.findViewById(R.id.handle);
				handle.setImageResource(R.drawable.show);

				WidgetUtil.setupSlideOpened(getActivity(), mHasData, slide);
			}
		});

		// Setup Navigation
		Button saveBtn = (Button) getView().findViewById(R.id.save_assess);
		Button summaryCmtBtn = (Button) getView().findViewById(R.id.summary_assess);
		Button summarySgtCmtBtn = (Button) getView().findViewById(R.id.summary_suggestion);
		Button cancelCmtBtn = (Button) getView().findViewById(R.id.cancel_assess);

		saveBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// Save AssessTran
				canBack = false;
				WidgetUtil.showProgress(mContentView, mProgressView, true);

				// Save Images on Server
				saveImageOnServer();
			}
		});

		summaryCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				savedTranPref.saveMap(projCycleStationId, saveAssessTran);
				FragmentManager fragmentManager = getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit).addToBackStack(null)
					.replace(R.id.container, SummaryAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, saveAssessTran)).commit();

			}
		});

		summarySgtCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				savedTranPref.saveMap(projCycleStationId, saveAssessTran);
				FragmentManager fragmentManager = getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit).addToBackStack(null)
					.replace(R.id.container, SummarySuggestionFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, saveAssessTran)).commit();

			}
		});

		cancelCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder cancelConfirm = new AlertDialog.Builder(getActivity());

				cancelConfirm.setTitle(getString(R.string.alert_confirm_cancel));
				cancelConfirm.setNegativeButton("Cancel", null);
				cancelConfirm.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int arg1) {

						FragmentManager fragmentManager = getFragmentManager();
						WidgetUtil.backPress(getActivity());

					}
				});
				cancelConfirm.show();

			}
		});

		if (!login.isAdmin()) {
			TextView nMapTxt = (TextView) getView().findViewById(R.id.map_assess);
			ImageView nMapImg = (ImageView) getView().findViewById(R.id.map_assess_prompt);
			nMapTxt.setVisibility(TextView.GONE);
			nMapImg.setVisibility(TextView.GONE);
		}
	}

	private void handleBackPressed() {
		// TODO Auto-generated method stub
		getView().setFocusableInTouchMode(true);
		getView().requestFocus();
		getView().setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {

				if (keyCode == KeyEvent.KEYCODE_BACK) {
					if(canBack) {
						WidgetUtil.backPress(getActivity());
					} else {
						return true;
					}
				}

				return false;
			}
		});
	}

	private void getLocationService() {
		try {
			// Google map
			if (!login.isAdmin()) {
				try {
					Fragment mapFragment = (Fragment) getFragmentManager().findFragmentById(R.id.map);
					if (mapFragment != null) {
						FragmentManager fragmentManager = getActivity().getFragmentManager();
						FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
						fragmentTransaction.remove(mapFragment);
						fragmentTransaction.commit();
					}
				} catch (Exception e) {
				}
				return;
			}

			map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

			map.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {

				@Override
				public void onMyLocationChange(Location location) {
					// TODO Auto-generated method stub
					try {
						if (saveAssessTran.GPSLocation != null && saveAssessTran.GPSLocation.length() != 0) {
							String[] saveLatLng = saveAssessTran.GPSLocation.split(AppUtil.COMMA);

							LatLng aLatLng = new LatLng(Double.parseDouble(saveLatLng[0]), Double.parseDouble(saveLatLng[1]));
							CameraPosition camPositon = new CameraPosition.Builder().target(aLatLng).zoom(Float.parseFloat(getString(R.string.map_zoom))).build();
							map.animateCamera(CameraUpdateFactory.newCameraPosition(camPositon));
							map.addMarker(new MarkerOptions().position(aLatLng));
							location.setLatitude(Double.parseDouble(saveLatLng[0]));
							location.setLongitude(Double.parseDouble(saveLatLng[1]));
							getGeoCoder(location);

						} else {
							TextView nMapTxt = (TextView) getView().findViewById(R.id.map_assess);
							nMapTxt.setText(getString(R.string.alert_no_map));
						}

					} catch (Exception e) {
						TextView nMapTxt = (TextView) getView().findViewById(R.id.map_assess);
						nMapTxt.setText(getString(R.string.alert_no_map));
					} finally {
						map.setMyLocationEnabled(false);
					}

				}

			});

			if (map != null) {
				map.setMyLocationEnabled(true);

			}
		} catch (Exception e) {
			TextView nMapTxt = (TextView) getView().findViewById(R.id.map_assess);
			nMapTxt.setText(getString(R.string.alert_no_map));
		}
	}

	private void setSubjectAndItemName() {
		// TODO Auto-generated method stub
		for (AssessItem assessItem : items.assessItem) {
			if (!subjectMap.containsKey(assessItem.CycleAssessSubjectId))
				subjectMap.put(assessItem.CycleAssessSubjectId, assessItem.AssessSubjectName);
			if (!itemChoiceMap.containsKey(assessItem.CycleAssessSubjectId))
				itemChoiceMap.put(assessItem.AssessItemId, assessItem.AssessItemName);
		}

	}

	public boolean isValid() {
		// TODO Auto-generated method stub
		boolean flag = true;
		Spinner yearSpin = (Spinner) getView().findViewById(R.id.year_assess);
		Spinner projSpin = (Spinner) getView().findViewById(R.id.project_assess);
		Spinner cycleSpin = (Spinner) getView().findViewById(R.id.cycle_assess);
		Spinner divSpin = (Spinner) getView().findViewById(R.id.div_assess);
		Spinner deptSpin = (Spinner) getView().findViewById(R.id.dept_assess);
		Spinner zoneSpin = (Spinner) getView().findViewById(R.id.zone_assess);
		AutoCompleteTextView stationAuto = (AutoCompleteTextView) getView().findViewById(R.id.station);

		// Validation Input
		TextView yearAlert = (TextView) getView().findViewById(R.id.year_alert);
		TextView projAlert = (TextView) getView().findViewById(R.id.project_alert);
		TextView cycleAlert = (TextView) getView().findViewById(R.id.cycle_alert);
		TextView stationAlert = (TextView) getView().findViewById(R.id.station_alert);

		if (search.shipToSelected == null || search.shipToSelected.length() == 0) {
			stationAlert.setError(getString(R.string.alert_required_field));
			stationAlert.requestFocus();
			flag = false;
		} else {
			stationAlert.setError(null);
		}
		if (cycleSpin.getSelectedItemPosition() == 0) {
			cycleAlert.setError(getString(R.string.alert_required_field));
			cycleAlert.requestFocus();
			flag = false;
		} else {
			cycleAlert.setError(null);
		}
		if (projSpin.getSelectedItemPosition() == 0) {
			projAlert.setError(getString(R.string.alert_required_field));
			projAlert.requestFocus();
			flag = false;
		} else {
			projAlert.setError(null);
		}
		if (yearSpin.getSelectedItemPosition() == 0) {
			yearAlert.setError(getString(R.string.alert_required_field));
			yearAlert.requestFocus();
			flag = false;
		} else {
			yearAlert.setError(null);
		}
		return flag;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.make_assess, container, false);
		return rootView;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		((MainActivity) activity).onSectionAttached(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER));
	}

	protected void getGeoCoder(Location location) {
		// TODO Auto-generated method stub
		// Set Geocoder
		GeocoderJSONCall geocoder = new GeocoderJSONCall(getString(R.string.geocoder_url));
		geocoder.setLatLng(getString(R.string.latLng), location.getLatitude(), location.getLongitude());

		mTask = new DefaultTask(geocoder, "");
		mTask.delegate = this;
		mTask.setMethod(getString(R.string.latLng));
		mTask.execute();

	}

	@Override
	public void processFinish(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			if (method.equals(getString(R.string.method_listassessitem)))
				getListAssessItem(method, output);
			else if (method.equals(getString(R.string.latLng))) {
				getLocationAddr(output);
			} else if (method.equals(getString(R.string.method_savedraftassesstran))) {
				getSaveDraft(method, output);
			} else if (method.equals(getString(R.string.method_getassesstran))) {
				getAssessTran(method, output);
			} else if (method.equals(getString(R.string.method_getassesstranlastupdate))) {
				getAssessTranLastUpdate(method, output);
			} else if (method.equals(getString(R.string.http_url))) {
				UploadImage(method, output);
			}

		} catch (Exception e) {
		}

	}

	private void UploadImage(String method, Object output) {
		// TODO Auto-generated method stub
		Log.i(method, "Call WS Success");
	}

	private void getAssessTranLastUpdate(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			AssessTranList assessTranLastUpdate = (AssessTranList) gson.fromJson((String) output, AssessTranList.class);
			if (assessTranLastUpdate != null) {
				saveAssessTran.RESOURCE_ID = assessTranLastUpdate.AssessTran5016_LasteUpdate.get(0).RESOURCE_ID;
				if (assessTranLastUpdate.AssessTran5016_LasteUpdate.get(0).Status.equals(AppUtil.ASSESS_STATUS_SUBMIT)) {

					Toast.makeText(getActivity(), getString(R.string.alert_already_submit), Toast.LENGTH_LONG).show();

					savedTranPref.ClearSavedAssessTran(projCycleStationId);
					isSubmit = false;

					PropertyInfo projProp = new PropertyInfo();
					projProp.setName(AppUtil.ProjectId);
					projProp.setValue(items.projectId);
					projProp.setType(String.class);

					PropertyInfo cycleProp = new PropertyInfo();
					cycleProp.setName(AppUtil.CycleAssessId);
					cycleProp.setValue(items.cycleAssessId);
					cycleProp.setType(String.class);

					PropertyInfo ResourceProp = new PropertyInfo();
					ResourceProp.setName(AppUtil.RESOURCE_ID);
					ResourceProp.setValue(saveAssessTran.RESOURCE_ID);
					ResourceProp.setType(String.class);

					PropertyInfo StationProp = new PropertyInfo();
					StationProp.setName(AppUtil.STATIONID);
					StationProp.setValue(items.stationId);
					StationProp.setType(String.class);

					Log.i("cycleAssessId", items.cycleAssessId);
					Log.i("projectId", items.projectId);
					Log.i("stationId", items.stationId);

					refreshSearchAssessData();

					mTask = new DefaultTask(com, getString(R.string.method_getassesstran));
					mTask.delegate = this;
					mTask.execute(ResourceProp, projProp, cycleProp, StationProp);
					return;
				}
			}
		
			SoapObject soap = WebserviceUtil.getAssessTran(AssessTran.AssessTranParam, saveAssessTran);

			PropertyInfo saveAssessProp = new PropertyInfo();
			saveAssessProp.setName(AssessTran.AssessTranParam);
			saveAssessProp.setValue(soap);
			saveAssessProp.setType(SoapObject.class);

			mTask = new DefaultTask(com, getString(R.string.method_savedraftassesstran));
			mTask.delegate = fragment;
			mTask.execute(saveAssessProp);

//			WidgetUtil.writeToFile(projCycleStationId, soap.toString());

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}
	}

	private void getAssessTranLastUpdate(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			AssessTranList assessTranLastUpdate = (AssessTranList) gson.fromJson((String) output, AssessTranList.class);
			if (assessTranLastUpdate == null)
				throw new Exception();

			if (saveAssessTran == null || saveAssessTran.Lastupdate.after(assessTranLastUpdate.AssessTran5016_LasteUpdate.get(0).Lastupdate)) {
				PropertyInfo projProp = new PropertyInfo();
				projProp.setName(AppUtil.ProjectId);
				projProp.setValue(items.projectId);
				projProp.setType(String.class);

				PropertyInfo cycleProp = new PropertyInfo();
				cycleProp.setName(AppUtil.CycleAssessId);
				cycleProp.setValue(items.cycleAssessId);
				cycleProp.setType(String.class);

				PropertyInfo ResourceProp = new PropertyInfo();
				ResourceProp.setName(AppUtil.RESOURCE_ID);
				ResourceProp.setValue(items.assessDataId);
				ResourceProp.setType(String.class);

				PropertyInfo StationProp = new PropertyInfo();
				StationProp.setName(AppUtil.STATIONID);
				StationProp.setValue(items.stationId);
				StationProp.setType(String.class);

				mTask = new DefaultTask(com, getString(R.string.method_getassesstran));
				mTask.delegate = this;
				mTask.execute(ResourceProp, projProp, cycleProp, StationProp);
			} else {
				if (saveAssessTran.RESOURCE_ID == null)
					saveAssessTran.RESOURCE_ID = items.assessDataId;
				if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT))
					isSubmit = true;

				getListNewAssessItem();

				canBack = true;
				WidgetUtil.showProgress(mContentView, mProgressView, false);

				TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
				mNoData.setVisibility(TextView.GONE);
				ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
				mHasData.setVisibility(ViewGroup.VISIBLE);
			}
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
			if (saveAssessTran != null) {
				if (saveAssessTran.RESOURCE_ID == null)
					saveAssessTran.RESOURCE_ID = items.assessDataId;
				if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT))
					isSubmit = true;
			} else {
				saveAssessTranStep1();
			}

			getListNewAssessItem();

			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);

			TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
			mNoData.setVisibility(TextView.GONE);
			ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
			mHasData.setVisibility(ViewGroup.VISIBLE);

		}
	}

	private void getAssessTran(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			AssessTran tempSaveAssessTran = (AssessTran) gson.fromJson((String) output, AssessTran.class);
			if (tempSaveAssessTran == null)
				throw new Exception();
			Log.i(method, "Cannot create Assess");

			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);			
			
			Toast.makeText(getActivity(), getString(R.string.alert_draft_assess), Toast.LENGTH_LONG).show();

			TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
			mNoData.setVisibility(TextView.VISIBLE);
			ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
			mHasData.setVisibility(ViewGroup.GONE);
		} catch (Exception e) {

			// Save AssessTran
			saveAssessTranStep1();

			Log.i(method, "Create Assess");

			// Show Assess Items
			getListNewAssessItem();

			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);

			TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
			mNoData.setVisibility(TextView.GONE);
			ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
			mHasData.setVisibility(ViewGroup.VISIBLE);
		}
	}

	private void getAssessTran(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			saveAssessTran = (AssessTran) gson.fromJson((String) output, AssessTran.class);

			saveAssessTran.StationName = items.stationName;
			saveAssessTran.ProjectName = items.projectName;
			saveAssessTran.CycleName = items.cycle;

			generateAssessItem();
			Log.i(method, "Call WS Success");
		} catch (Exception e) {

			// Save AssessTran
			saveAssessTranStep1();
			Log.i(method, "Call WS Failed");
		}

		try {
			// Show Assess Items
			getListNewAssessItem();

			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);

			TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
			mNoData.setVisibility(TextView.GONE);
			ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
			mHasData.setVisibility(ViewGroup.VISIBLE);
		} catch (Exception e) {

			TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
			mNoData.setVisibility(TextView.VISIBLE);
			ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
			mHasData.setVisibility(ViewGroup.GONE);

			Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
			Log.i(method, "Call WS Failed");
		}
	}

	private void generateAssessItem() {
		// TODO Auto-generated method stub

		if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT))
			isSubmit = true;

		for (AssessSubject5019 subject : saveAssessTran.Subjects.get(0).AssessSubject5019) {
			SummaryAssess mSummary = new SummaryAssess();

			for (AssessItemChoice5018 item : subject.Items.get(0).AssessItemChoice) {
				subject.Items.get(0).AssessItemChoiceMap.put(item.AssessItemId, item);
				if (!saveAssessTran.Subjects.get(0).AssessSubject5019Map.containsKey(item.CycleAssessSubjectId))
					saveAssessTran.Subjects.get(0).AssessSubject5019Map.put(item.CycleAssessSubjectId, subject);
				mSummary.subjectId = item.CycleAssessSubjectId;
				mSummary.subjectName = subjectMap.get(item.CycleAssessSubjectId);
				item.AssessSubjectName = subjectMap.get(item.CycleAssessSubjectId);
				item.AssessItemName = itemChoiceMap.get(item.AssessItemId);
				if (item.AssessChoicePoint.length() != 0)
					itemRows.put(item.CycleAssessSubjectId + AppUtil.UNDER_SCROLL + item.AssessItemId, item.AssessChoicePoint + AppUtil.UNDER_SCROLL + item.AssessChoicePoint + AppUtil.UNDER_SCROLL
						+ item.AssessChoiceId);
				if (item.Suggestions != null) {
					for (AssessSuggestion5034 suggestion : item.Suggestions.get(0).AssessSuggestion5034) {
						item.Suggestions.get(0).AssessSuggestion5034Map.put(AppUtil.NEW_SUGGESTION + suggestion.AssessSuggestionIndex, suggestion);
					}
				}
			}

			// Add Summary from GetAssessTran
			mSummary.subjectTotal = subject.WeightPoint;
			mSummary.sumTotal = subject.TotalRawPoint;
			mSummary.netTotal = subject.TotalFullPoint;
			mSummary.percentTotal = (int) (((double) subject.TotalRawPoint / (double) subject.TotalFullPoint) * 100);
			mSummary.weightTotal = (int) (((double) subject.TotalRawPoint / (double) subject.TotalFullPoint) * subject.WeightPoint);
			mSummary.UserComment = subject.UserComment;

			summaryAssess.put(mSummary.subjectId, mSummary);

		}

		saveSummaryPref.saveMap(projCycleStationId, summaryAssess);
		savedTranPref.saveMap(projCycleStationId, saveAssessTran);

	}

	private void getSaveDraft(String method, Object output) {
		// TODO Auto-generated method stub
		output = "{" + output + "}";

		try {
			SaveDraftAssessTranResult SaveDraftAssessTranResult = (SaveDraftAssessTranResult) gson.fromJson((String) output, SaveDraftAssessTranResult.class);

			Toast.makeText(getActivity(), getString(R.string.alert_save_draft), Toast.LENGTH_LONG).show();

			savedTranPref.ClearSavedAssessTran(projCycleStationId);
			isSubmit = false;
			

			PropertyInfo projProp = new PropertyInfo();
			projProp.setName(AppUtil.ProjectId);
			projProp.setValue(items.projectId);
			projProp.setType(String.class);

			PropertyInfo cycleProp = new PropertyInfo();
			cycleProp.setName(AppUtil.CycleAssessId);
			cycleProp.setValue(items.cycleAssessId);
			cycleProp.setType(String.class);

			PropertyInfo ResourceProp = new PropertyInfo();
			ResourceProp.setName(AppUtil.RESOURCE_ID);
			ResourceProp.setValue(saveAssessTran.RESOURCE_ID);
			ResourceProp.setType(String.class);

			PropertyInfo StationProp = new PropertyInfo();
			StationProp.setName(AppUtil.STATIONID);
			StationProp.setValue(items.stationId);
			StationProp.setType(String.class);

			Log.i("Test", items.cycleAssessId);
			Log.i("Test", items.projectId);
			Log.i("Test", items.stationId);

			refreshSearchAssessData();

			mTask = new DefaultTask(com, getString(R.string.method_getassesstran));
			mTask.delegate = this;
			mTask.execute(ResourceProp, projProp, cycleProp, StationProp);

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");

			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);

			TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
			mNoData.setVisibility(TextView.GONE);
			ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
			mHasData.setVisibility(ViewGroup.VISIBLE);
		}
	}

	private void saveImageOnServer() {
		// TODO Auto-generated method stub
		try {
			List<SuggestionImage> deviceImages = new ArrayList<SuggestionImage>();
			List<SuggestionImage> serverImages = new ArrayList<SuggestionImage>();
			for (AssessSubject5019 subject : saveAssessTran.Subjects.get(0).AssessSubject5019Map.values()) {

				for (AssessItemChoice5018 item : subject.Items.get(0).AssessItemChoiceMap.values()) {

					if (item.AssessChoicePoint.length() != 0)

						if (item.Suggestions != null && item.Suggestions.size() != 0) {

							for (AssessSuggestion5034 suggestion : item.Suggestions.get(0).AssessSuggestion5034Map.values()) {
								if (suggestion.Images != null && suggestion.Images.size() != 0) {
									for (SuggestionImage image : suggestion.Images.get(0).SuggestionImage) {
										// CR 107, 108
										if (image.CreatedDt == null || image.CreatedDt.length() == 0) {
											deviceImages.add(image);
										} else {
											serverImages.add(image);

										}
									}

									if (serverImages.size() != 0) {
										for (SuggestionImage image : serverImages) {
											suggestion.Images.get(0).SuggestionImage.remove(image);
										}
										serverImages = new ArrayList<SuggestionImage>();
									}

								}
							}
						}
				}
			}

			if (deviceImages.size() != 0) {
				setCount(deviceImages.size());
				for (SuggestionImage image : deviceImages) {
					uploadCall = UploadCall.getInstance();

					PropertyInfo nameProp = new PropertyInfo();
					nameProp.setValue(image.FILE_SAVE_NAME);
					nameProp.setType(String.class);

					PropertyInfo bitmapProp = new PropertyInfo();
					bitmapProp.setValue(WidgetUtil.getImageOnDevice(getActivity(), image.FILE_SAVE_NAME));
					bitmapProp.setType(Bitmap.class);

					mTask = new DefaultTask(uploadCall, getString(R.string.http_url), image);
					mTask.delegate = fragment;
					mTask.execute(nameProp, bitmapProp);

					Log.i("save image count", "T");
				}
			} else {
				onDecrementCount();
			}
		} catch (Exception e) {
			// TODO: handle exception
			Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
		}

	}

	private void getLocationAddr(Object output) {
		// TODO Auto-generated method stub
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject = new JSONObject((String) output);
			String addr = ((JSONArray) jsonObject.get(AppUtil.GEO_RESULT)).getJSONObject(0).getString(AppUtil.GEO_FORMAT_ADDR);

			TextView nMapTxt = (TextView) getView().findViewById(R.id.map_assess);
			nMapTxt.setText(addr);

			nMapTxt.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					RelativeLayout container = (RelativeLayout) getView().findViewById(R.id.map_container);
					container.setVisibility(LinearLayout.VISIBLE);
				}
			});

			ImageView mBack = (ImageView) getView().findViewById(R.id.back_make_assess);
			mBack.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					RelativeLayout container = (RelativeLayout) getView().findViewById(R.id.map_container);
					container.setVisibility(LinearLayout.GONE);
				}
			});

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			TextView nMapTxt = (TextView) getView().findViewById(R.id.map_assess);
			nMapTxt.setText(getString(R.string.alert_no_map));
		}
	}

	public void getListAssessItem(String method, Object output) {
		// TODO Auto-generated method stub
		canBack = true;
		WidgetUtil.showProgress(mContentView, mProgressView, false);
		try {
			clearSearchAssessData();

			String tempStationId = search.assessItemList.stationId;
			String tempStationName = search.assessItemList.stationName;
			String tempLocationId = search.assessItemList.locationId;
			String tempProjId = search.assessItemList.projectId;
			String tempProjName = search.assessItemList.projectName;
			String tempCycleId = search.assessItemList.cycleAssessId;
			String tempCycle = search.assessItemList.cycle;
			String tempYearId = search.assessItemList.yearAssessId;
			String tempAssessDataId = search.assessItemList.assessDataId;
			search.assessItemList = (AssessItemList) gson.fromJson((String) output, AssessItemList.class);

			search.assessItemList.stationId = tempStationId;
			search.assessItemList.stationName = tempStationName;
			search.assessItemList.locationId = tempLocationId;
			search.assessItemList.projectId = tempProjId;
			search.assessItemList.projectName = tempProjName;
			search.assessItemList.cycle = tempCycle;
			search.assessItemList.cycleAssessId = tempCycleId;
			search.assessItemList.yearAssessId = tempYearId;
			search.assessItemList.assessDataId = tempAssessDataId;
			items = search.assessItemList;

			projCycleStationId = items.projectId + AppUtil.UNDER_SCROLL + items.cycleAssessId + AppUtil.UNDER_SCROLL + items.stationId + AppUtil.UNDER_SCROLL + login.User_Group_Code;
			Log.i("step id", projCycleStationId);

			// Location Services
			getLocationService();

			// Show Header
			saveItemPref = new SavedItemAssess(getActivity().getApplicationContext());
			itemRows = saveItemPref.loadMap(projCycleStationId);
			saveSummaryPref = new SavedSummaryAssess(getActivity().getApplicationContext());
			summaryAssess = saveSummaryPref.loadMap(projCycleStationId);

			((TextView) getView().findViewById(R.id.station_value)).setText(items.stationId + AppUtil.SPACE + items.stationName);
			((TextView) getView().findViewById(R.id.project_assess_value)).setText(items.projectName);
			((TextView) getView().findViewById(R.id.cycle_assess_value)).setText(items.cycle);
			((TextView) getView().findViewById(R.id.pbl)).setText(items.locationId);
			if (!login.isAdmin()) {
				((TextView) getView().findViewById(R.id.fullname_assess_value)).setText(login.User_Name);
				((TextView) getView().findViewById(R.id.group_assess_value)).setText(login.User_Group_Name);
			}

			isSubmit = false;

			// Get AssessTran
			saveAssessTranStep1_isDraft();
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
			TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
			mNoData.setVisibility(TextView.VISIBLE);
			ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
			mHasData.setVisibility(ViewGroup.GONE);
		}

	}

	protected void getAssessItemService(String project, String cycle) {
		// TODO Auto-generated method stub
		PropertyInfo projProp = new PropertyInfo();
		projProp.setName(AssessItem.ProjectId);
		projProp.setValue(project);
		projProp.setType(String.class);

		PropertyInfo cycleProp = new PropertyInfo();
		cycleProp.setName(AssessItem.Cycle);
		cycleProp.setValue(cycle);
		cycleProp.setType(String.class);

		mTask = new DefaultTask(com, getString(R.string.method_listassessitem));
		mTask.delegate = this;
		mTask.execute(projProp, cycleProp);
	}

	private void getListNewAssessItem() {
		// TODO Auto-generated method stub
		try {
			((TextView) getView().findViewById(R.id.assess_date_value)).setText(AppUtil.formatter_EN_FULL3.format(saveAssessTran.CreateDate));
			if (login.isAdmin()) {
				((TextView) getView().findViewById(R.id.fullname_assess_value)).setText(saveAssessTran.UserName);
				((TextView) getView().findViewById(R.id.group_assess_value)).setText(saveAssessTran.UserTypeName);
			}

			if (isSubmit) {
				((Button) getView().findViewById(R.id.save_assess)).setVisibility(Button.GONE);

				((TextView) getView().findViewById(R.id.submit_date_prompt)).setVisibility(TextView.VISIBLE);
				((TextView) getView().findViewById(R.id.submit_date_value)).setVisibility(TextView.VISIBLE);
				((TextView) getView().findViewById(R.id.submit_date_value)).setText(AppUtil.formatter_EN_FULL3.format(saveAssessTran.SubmitDate));
			} else {
				((TextView) getView().findViewById(R.id.submit_date_prompt)).setVisibility(TextView.INVISIBLE);
				((TextView) getView().findViewById(R.id.submit_date_value)).setVisibility(TextView.INVISIBLE);
			}

			final TextView next = (TextView) getView().findViewById(R.id.next_subject);
			final TextView prev = (TextView) getView().findViewById(R.id.prev_subject);
			final TextView detail = (TextView) getView().findViewById(R.id.detail_make_assess);

			boolean isFirstRow = true;
			List<AssessItem> itemList = new ArrayList<AssessItem>();

			for (AssessItem item : items.assessItem) {

				if (!itemMap.containsKey(item.AssessSubjectName) || isFirstRow) {
					itemList = new ArrayList<AssessItem>();
					itemMap.put(item.AssessSubjectName, itemList);
					subjectKeys.add(item.AssessSubjectName);
					isFirstRow = false;
				}
				itemList.add(item);
			}

			if (curSubject != 0) {
				numSubject = curSubject;
			}

			// Start First-Item
			prev.setVisibility(TextView.INVISIBLE);
			next.setVisibility(TextView.INVISIBLE);
			detail.setText(subjectKeys.get(numSubject));
			detail.setVisibility(TextView.VISIBLE);

			if (numSubject != 0) {
				prev.setVisibility(TextView.VISIBLE);
			}

			if (numSubject != subjectKeys.size() - 1) {
				next.setVisibility(TextView.VISIBLE);
			}

			getListAssessItemDetail();
			// End First-Item
			next.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					int inBound = numSubject + 1;
					if (inBound < subjectKeys.size()) {
						numSubject++;
						detail.setText(subjectKeys.get(numSubject));
						if (numSubject != subjectKeys.size() - 1) {
							next.setVisibility(TextView.VISIBLE);
							prev.setVisibility(TextView.VISIBLE);
						} else
							next.setVisibility(TextView.INVISIBLE);

						getListAssessItemDetail();
					}
				}
			});

			prev.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					int inBound = numSubject - 1;
					if (inBound > -1) {
						numSubject--;
						detail.setText(subjectKeys.get(numSubject));
						if (numSubject != 0) {
							next.setVisibility(TextView.VISIBLE);
							prev.setVisibility(TextView.VISIBLE);
						} else
							prev.setVisibility(TextView.INVISIBLE);

						getListAssessItemDetail();
					}
				}
			});

		} catch (Exception e) {
			Log.i("list", e.toString());
		}
	}

	private void getListAssessItemDetail() {
		final List<AssessItem> curItems = (List<AssessItem>) itemMap.get(subjectKeys.get(numSubject));

		Collections.sort(curItems, new Comparator() {

			@Override
			public int compare(Object arg0, Object arg1) {
				// TODO Auto-generated method stub
				return new Integer(((AssessItem) arg0).AssessItemIndex).compareTo(new Integer(((AssessItem) arg1).AssessItemIndex));
			}

		});

		// Make Assess List
		makeAssessList = new MakeAssessList();
		makeAssessList.makeAssesses = new ArrayList<MakeAssess>();
		for (AssessItem curItem : curItems) {

			AssessItemChoice5018 item = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(curItem.CycleAssessSubjectId).Items.get(0).AssessItemChoiceMap.get(curItem.AssessItemId);
			String status = "";
			boolean isRemark = false;
			if (item.Suggestions == null || item.Suggestions.size() == 0 || item.Suggestions.get(0).AssessSuggestion5034Map == null || item.Suggestions.get(0).AssessSuggestion5034Map.size() == 0) {

				if (item.AssessChoicePoint.equals(String.valueOf(curItem.MaxPoint)) || item.AssessChoicePoint.equals(AppUtil.NA)) {
					status = AppUtil.ASSESS_STATUS_SUBMIT;
				} else if (item.AssessChoicePoint == null || item.AssessChoicePoint.length() == 0) {
					status = AppUtil.ASSESS_STATUS_NONE;
				} else {
					status = AppUtil.ASSESS_STATUS_DRAFT;
				}
			} else {
				isRemark = true;
				if ((item.AssessChoicePoint == null || item.AssessChoicePoint.length() == 0) && !item.AssessChoicePoint.equals(AppUtil.NA)) {
					status = AppUtil.ASSESS_STATUS_NONE;
				} else {
					status = AppUtil.ASSESS_STATUS_SUBMIT;
				}
			}
			item.Status = status;

			MakeAssess assessInput = new MakeAssess();
			assessInput.subjectId = curItem.CycleAssessSubjectId;
			assessInput.subjectName = curItem.AssessSubjectName;
			assessInput.itemId = curItem.AssessItemId;
			assessInput.status = status;
			assessInput.itemName = curItem.AssessItemIndex + AppUtil.SPACE + curItem.AssessItemName;
			assessInput.isRemark = isRemark;
			assessInput.AssessItemPoints = curItem.AssessItemPoints.get(0) != null ? curItem.AssessItemPoints.get(0).AssessItemPoint : null;
			assessInput.max = curItem.MaxPoint;
			assessInput.weight = curItem.CycleAssessSubjectPoint;
			makeAssessList.makeAssesses.add(assessInput);
		}

		final TableLayout table = (TableLayout) getView().findViewById(R.id.make_table);
		table.removeAllViews();

		ScrollView mScroll = (ScrollView) getView().findViewById(R.id.information_view);
		mScroll.scrollTo(0, 0);

		// Inflate your row "template" and fill out the fields.
		for (final MakeAssess makeAssess : makeAssessList.makeAssesses) {
			TableRow row = (TableRow) LayoutInflater.from(MakeAssessFragment.this.getActivity()).inflate(R.layout.make_row, null);

			final ImageView status = (ImageView) row.findViewById(R.id.status);
			final TextView assessName = (TextView) row.findViewById(R.id.assess_name);
			ImageView isRemark = (ImageView) row.findViewById(R.id.remark);
			final Spinner choices = (Spinner) row.findViewById(R.id.rating);

			if (makeAssess.status.equals(AppUtil.ASSESS_STATUS_DRAFT)) {
				status.setImageResource(R.drawable.status_assess_draft);
			} else if (makeAssess.status.equals(AppUtil.ASSESS_STATUS_SUBMIT)) {
				status.setImageResource(R.drawable.status_assess_submit);
			} else if (makeAssess.status.equals(AppUtil.ASSESS_STATUS_NONE)) {
				status.setImageResource(R.drawable.status_assess_none);
			}

			if (makeAssess.itemName != null) {
				assessName.setText(makeAssess.itemName);
			}

			if (makeAssess.isRemark) {
				isRemark.setImageResource(R.drawable.comment);
			} else {
				isRemark.setImageResource(R.drawable.nocomment);
			}

			isRemark.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AssessItemChoice5018 item = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(makeAssess.subjectId).Items.get(0).AssessItemChoiceMap.get(makeAssess.itemId);
					if (!(item.AssessChoicePoint == null || item.AssessChoicePoint.length() == 0)) {
						savedTranPref.saveMap(projCycleStationId, saveAssessTran);
						FragmentManager fragmentManager = getActivity().getFragmentManager();
						FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
						fragmentTransaction
							.setCustomAnimations(R.anim.enter, R.anim.exit)
							.addToBackStack(null)
							.replace(R.id.container,
								CommentAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, saveAssessTran, makeAssess.subjectId, makeAssess.itemId, numSubject))
							.commit();
					}
				}
			});

			if (isSubmit) {
				choices.setEnabled(false);
				choices.setClickable(false);
			}

			if (makeAssess.AssessItemPoints != null) {

				List<SpinnerObject> arr = new ArrayList<SpinnerObject>();
				arr.add(new SpinnerObject("", "", ""));
				for (AssessItemPoint choice : makeAssess.AssessItemPoints) {
					arr.add(new SpinnerObject(choice.AssessChoiceId, choice.Point_Name, choice.Point));
				}
				ArrayAdapter<SpinnerObject> arrAdt = new ArrayAdapter<SpinnerObject>(getActivity(), android.R.layout.simple_spinner_dropdown_item, arr);
				arrAdt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

				choices.setAdapter(arrAdt);
				if (itemRows.get(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId) != null) {
					Iterator iter = arr.iterator();
					int position = 0;
					while (iter.hasNext()) {

						SpinnerObject obj = (SpinnerObject) iter.next();
						if (obj.getId().equalsIgnoreCase(itemRows.get(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId).split(AppUtil.UNDER_SCROLL)[2]))
							break;
						position++;

					}
					choices.setSelection(position);
					// choices.setSelection(Integer.parseInt(itemRows.get(makeAssess.subjectId
					// + AppUtil.UNDER_SCROLL +
					// makeAssess.itemId).split(AppUtil.UNDER_SCROLL)[0]));
				}
				choices.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
						// TODO Auto-generated method stub

						// Calculate Total Point
						calculateSelectedPoint(makeAssess, parent, pos);

						// Save AssessTran
						SpinnerObject selected = ((SpinnerObject) parent.getSelectedItem());
						saveAssessTranStep2_saveScore(makeAssess.subjectId, makeAssess.itemId, selected.getId(), selected.getValue(), selected.getName());

						// Update Status
						AssessItemChoice5018 item = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(makeAssess.subjectId).Items.get(0).AssessItemChoiceMap.get(makeAssess.itemId);

						if (item.Suggestions == null || item.Suggestions.size() == 0 || item.Suggestions.get(0).AssessSuggestion5034Map == null
							|| item.Suggestions.get(0).AssessSuggestion5034Map.size() == 0) {
							if (item.AssessChoicePoint.equals(String.valueOf(makeAssess.max)) || item.AssessChoicePoint.equals(AppUtil.NA)) {
								status.setImageResource(R.drawable.status_assess_submit);
								item.Status = AppUtil.ASSESS_STATUS_SUBMIT;
							} else if (item.AssessChoicePoint == null || item.AssessChoicePoint.length() == 0) {
								status.setImageResource(R.drawable.status_assess_none);
								item.Status = AppUtil.ASSESS_STATUS_NONE;
							} else {
								status.setImageResource(R.drawable.status_assess_draft);
								item.Status = AppUtil.ASSESS_STATUS_DRAFT;
							}
						} else {
							if ((item.AssessChoicePoint == null || item.AssessChoicePoint.length() == 0) && !item.AssessChoicePoint.equals(AppUtil.NA)) {
								status.setImageResource(R.drawable.status_assess_none);
								item.Status = AppUtil.ASSESS_STATUS_NONE;
							} else {
								status.setImageResource(R.drawable.status_assess_submit);
								item.Status = AppUtil.ASSESS_STATUS_SUBMIT;
							}
						}

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}

				});
			}

			table.addView(row);
		}
		table.requestLayout();

		// Calculate Total Point
		calculatePoint(makeAssessList);

		// Set UserComment
		setUserComment(curItems.get(0).CycleAssessSubjectId);

		// Set Default-NA
		Button mDefaultNA = (Button) getView().findViewById(R.id.default_na);
		if (!isSubmit) {
			mDefaultNA.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					for (int index2 = 0; index2 < table.getChildCount(); index2++) {
						TableRow row = (TableRow) table.getChildAt(index2);
						Spinner choices = (Spinner) row.findViewById(R.id.rating);
						SpinnerObject point = (SpinnerObject) choices.getItemAtPosition(choices.getCount() - 1);
						if (AppUtil.NA.equalsIgnoreCase(point.getValue()) && choices.getSelectedItemPosition() == 0) {
							choices.setSelection(choices.getCount() - 1);
						}

					}

				}
			});
		} else {
			mDefaultNA.setVisibility(Button.INVISIBLE);
		}

		// Set Default-Good
		Button mDefaultGood = (Button) getView().findViewById(R.id.default_good);
		if (!isSubmit) {
			mDefaultGood.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub

					for (int index2 = 0; index2 < table.getChildCount(); index2++) {
						TableRow row = (TableRow) table.getChildAt(index2);
						Spinner choices = (Spinner) row.findViewById(R.id.rating);
						SpinnerObject point = (SpinnerObject) choices.getItemAtPosition(choices.getCount() - 1);

						choices.setSelection(1);

					}

				}
			});
		} else {
			mDefaultGood.setVisibility(Button.INVISIBLE);
		}

	}

	private void calculateSelectedPoint(MakeAssess makeAssess, AdapterView<?> parent, int pos) {
		TextView mNetTotal = (TextView) getView().findViewById(R.id.net_total);
		TextView mSumTotal = (TextView) getView().findViewById(R.id.sum_total);
		TextView mPercentTotal = (TextView) getView().findViewById(R.id.percent_total);
		TextView mWeightTotal = (TextView) getView().findViewById(R.id.weight_total);
		TextView mSubjectTotal = (TextView) getView().findViewById(R.id.subject_total);

		int sumTotal = Integer.parseInt(mSumTotal.getText().toString());
		int netTotal = Integer.parseInt(mNetTotal.getText().toString());
		int weight = Integer.parseInt(makeAssess.weight);
		if (itemRows.get(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId) != null) {
			String pointName = itemRows.get(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId).split(AppUtil.UNDER_SCROLL)[1];
			if (pointName.equalsIgnoreCase(AppUtil.NA)) {
				netTotal += Integer.parseInt(makeAssess.max);
			} else {
				int point = Integer.parseInt(pointName);
				sumTotal -= point;
			}
			itemRows.remove(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId);
		}

		if (pos != 0) {
			SpinnerObject selected = ((SpinnerObject) parent.getSelectedItem());
			itemRows.put(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId, String.valueOf(pos) + AppUtil.UNDER_SCROLL + selected.getValue() + AppUtil.UNDER_SCROLL + selected.getId());
		}

		String pointName = itemRows.get(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId) != null ? itemRows.get(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId).split(
			AppUtil.UNDER_SCROLL)[1] : "0";

		if (pointName.equalsIgnoreCase(AppUtil.NA)) {
			netTotal -= Integer.parseInt(makeAssess.max);
		} else {
			int point = Integer.parseInt(pointName);
			sumTotal += point;
		}

		int weightTotal = Math.round(((float) sumTotal / (float) netTotal) * weight);

		int percentTotal = Math.round(((float) sumTotal / (float) netTotal) * 100);

		mSumTotal.setText(String.valueOf(sumTotal));
		mNetTotal.setText(String.valueOf(netTotal));
		mPercentTotal.setText(String.valueOf(percentTotal) + AppUtil.PERCENT);
		mWeightTotal.setText(String.valueOf(weightTotal));
		mSubjectTotal.setText(getString(R.string.subject_total).replaceAll("@0", String.valueOf(weight)));
		mSubjectTotal.setVisibility(TextView.VISIBLE);

		SummaryAssess mSummary = new SummaryAssess();
		mSummary.sumTotal = sumTotal;
		mSummary.netTotal = netTotal;
		mSummary.percentTotal = percentTotal;
		mSummary.subjectTotal = weight;
		mSummary.weightTotal = weightTotal;
		mSummary.subjectName = makeAssessList.makeAssesses.get(0).subjectName;
		mSummary.subjectId = makeAssessList.makeAssesses.get(0).subjectId;
		mSummary.UserComment = summaryAssess.get(mSummary.subjectId) != null ? summaryAssess.get(mSummary.subjectId).UserComment : null;
		summaryAssess.put(mSummary.subjectId, mSummary);
		saveSummaryPref.saveMap(projCycleStationId, summaryAssess);

	}

	private void calculatePoint(MakeAssessList makeAssessList) {
		TextView mNetTotal = (TextView) getView().findViewById(R.id.net_total);
		TextView mSumTotal = (TextView) getView().findViewById(R.id.sum_total);
		TextView mPercentTotal = (TextView) getView().findViewById(R.id.percent_total);
		TextView mWeightTotal = (TextView) getView().findViewById(R.id.weight_total);
		TextView mSubjectTotal = (TextView) getView().findViewById(R.id.subject_total);
		int netTotal = 0;
		int sumTotal = 0;
		int weight = Integer.parseInt(makeAssessList.makeAssesses.get(0).weight);

		for (MakeAssess makeAssess : makeAssessList.makeAssesses) {

			String pointName = itemRows.get(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId) != null ? itemRows.get(makeAssess.subjectId + AppUtil.UNDER_SCROLL + makeAssess.itemId)
				.split(AppUtil.UNDER_SCROLL)[1] : "0";

			if (!pointName.equalsIgnoreCase(AppUtil.NA)) {
				int point = Integer.parseInt(pointName);
				sumTotal += point;
				netTotal += Integer.parseInt(makeAssess.max);
			}

		}
		int weightTotal = Math.round(((float) sumTotal / (float) netTotal) * weight);

		int percentTotal = Math.round(((float) sumTotal / (float) netTotal) * 100);

		mSumTotal.setText(String.valueOf(sumTotal));
		mNetTotal.setText(String.valueOf(netTotal));
		mPercentTotal.setText(String.valueOf(percentTotal) + AppUtil.PERCENT);
		mWeightTotal.setText(String.valueOf(weightTotal));
		mSubjectTotal.setText(getString(R.string.subject_total).replaceAll("@0", String.valueOf(weight)));
		mSubjectTotal.setVisibility(TextView.VISIBLE);

		SummaryAssess mSummary = new SummaryAssess();
		mSummary.sumTotal = sumTotal;
		mSummary.netTotal = netTotal;
		mSummary.subjectTotal = weight;
		mSummary.percentTotal = percentTotal;
		mSummary.weightTotal = weightTotal;
		mSummary.subjectName = makeAssessList.makeAssesses.get(0).subjectName;
		mSummary.subjectId = makeAssessList.makeAssesses.get(0).subjectId;
		mSummary.UserComment = summaryAssess.get(mSummary.subjectId) != null ? summaryAssess.get(mSummary.subjectId).UserComment : null;
		summaryAssess.put(mSummary.subjectId, mSummary);
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		// Saved Item Assess on pref
		if (projCycleStationId != null) {
			saveItemPref.saveMap(projCycleStationId, itemRows);
			saveSummaryPref.saveMap(projCycleStationId, summaryAssess);
			savedTranPref.saveMap(projCycleStationId, saveAssessTran);

			Log.i("onStop", "Save Draft on this device");
		}

		try {
			Fragment mapFragment = (Fragment) getFragmentManager().findFragmentById(R.id.map);
			if (mapFragment != null) {
				FragmentManager fragmentManager = getActivity().getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.remove(mapFragment);
				fragmentTransaction.commit();
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
		try {
			Fragment mapFragment = (Fragment) getFragmentManager().findFragmentById(R.id.map);
			if (mapFragment != null) {
				FragmentManager fragmentManager = getActivity().getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.remove(mapFragment);
				fragmentTransaction.commit();
			}
		} catch (Exception e) {
		}

	}

	public void clearSearchAssess() {
		search.shipToSelected = "";

		Spinner removeSpin = (Spinner) getActivity().findViewById(R.id.year_assess);
		removeSpin.setSelection(0);

		removeSpin = (Spinner) getActivity().findViewById(R.id.div_assess);
		removeSpin.setSelection(0);

		List<String> removearr = new ArrayList<String>();
		removearr.add(getString(R.string.header_spinner));
		ArrayAdapter<String> removeAdt = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, removearr);

		removeSpin = (Spinner) getActivity().findViewById(R.id.project_assess);
		removeSpin.setAdapter(removeAdt);

		removeSpin = (Spinner) getActivity().findViewById(R.id.cycle_assess);
		removeSpin.setAdapter(removeAdt);

		removeSpin = (Spinner) getActivity().findViewById(R.id.dept_assess);
		removeSpin.setAdapter(removeAdt);

		removeSpin = (Spinner) getActivity().findViewById(R.id.zone_assess);
		removeSpin.setAdapter(removeAdt);

		AutoCompleteTextView autoComplete = (AutoCompleteTextView) getView().findViewById(R.id.station);
		autoComplete.setText("");

	}

	public void clearSearchAssessData() {
		// Clear Search Data
		saveAssessTran = new AssessTran();

		items = new AssessItemList();

		itemMap = new TreeMap<String, List<AssessItem>>();

		subjectKeys = new ArrayList<String>();

		itemRows = new TreeMap<String, String>();

		summaryAssess = new TreeMap<String, SummaryAssess>();

		numSubject = 0;

		curSubject = 0;

		isCurrentFirst = false;
	}

	public void refreshSearchAssessData() {
		// Clear Search Data
		saveAssessTran = new AssessTran();

		itemMap = new TreeMap<String, List<AssessItem>>();

		subjectKeys = new ArrayList<String>();

		numSubject = 0;

		curSubject = 0;
	}

	@Override
	public void processFinish(String method, Object output, Object... objects) {
		try {
			// TODO Auto-generated method stub
			if (method.equals(getString(R.string.method_getassesstran))) {
				getAssessTran(method, output, objects);
			} else if (method.equals(getString(R.string.method_getassesstranlastupdate))) {
				getAssessTranLastUpdate(method, output, objects);
			} else if (method.equals(getString(R.string.http_url))) {
				UploadImage(method, output, objects);
			}
		} catch (Exception e) {
			Log.i("error", e.toString());
		}
	}

	private void setUserComment(final String subjectId) {
		// TODO Auto-generated method stub
		TextView mComment = (TextView) getView().findViewById(R.id.comment_assess);
		SummaryAssess summary = summaryAssess.get(subjectId);
		mComment.setText(summary.UserComment);
		if (!isSubmit)
			mComment.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
					alert.setTitle(getString(R.string.comment_assess_prompt));
					LayoutInflater factory = LayoutInflater.from(getActivity());
					final View textEntryView = factory.inflate(R.layout.multiline_input, null);

					final EditText mMultiText = (EditText) textEntryView.findViewById(R.id.multiline_input);
					final TextView mComment = (TextView) getView().findViewById(R.id.comment_assess);
					mMultiText.setText(mComment.getText().toString(), TextView.BufferType.SPANNABLE);
					mMultiText.setSelection(mComment.getText().toString().length());

					alert.setView(textEntryView);

					alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							mComment.setText(mMultiText.getText().toString());
							saveAssessTranStep2_saveUserComment(subjectId, mMultiText.getText().toString());
							return;
						}
					});

					alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							return;
						}
					});

					final AlertDialog dialog = alert.create();
					dialog.show();

					List<View> errors = new ArrayList<View>();
					errors.add((EditText) textEntryView.findViewById(R.id.multiline_input));

					WidgetUtil.validateMaxlengthData(getActivity(), (EditText) textEntryView.findViewById(R.id.multiline_input), dialog, Integer.parseInt(getString(R.string.maxlength)), errors);
				}
			});
	}

	private void saveAssessTranStep1_isDraft() {
		savedTranPref = new SavedAssessTran(getActivity().getApplicationContext());
		saveAssessTran = savedTranPref.loadMap(projCycleStationId);

		if (!isDraft) {
			// First Page Load
			PropertyInfo projProp = new PropertyInfo();
			projProp.setName(AppUtil.ProjectId);
			projProp.setValue(items.projectId);
			projProp.setType(String.class);

			PropertyInfo cycleProp = new PropertyInfo();
			cycleProp.setName(AppUtil.CycleAssessId);
			cycleProp.setValue(items.cycleAssessId);
			cycleProp.setType(String.class);

			PropertyInfo ResourceProp = new PropertyInfo();
			ResourceProp.setName(AppUtil.UserTypeId);
			ResourceProp.setValue(login.User_Group_Code);
			ResourceProp.setType(String.class);

			PropertyInfo StationProp = new PropertyInfo();
			StationProp.setName(AppUtil.STATIONID);
			StationProp.setValue(items.stationId);
			StationProp.setType(String.class);

			mTask = new DefaultTask(com, getString(R.string.method_getassesstranlastupdate));
			mTask.delegate = this;
			mTask.execute(ResourceProp, projProp, cycleProp, StationProp);
		} else {
			if (saveAssessTran.RESOURCE_ID == null)
				saveAssessTran.RESOURCE_ID = items.assessDataId;
			if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT))
				isSubmit = true;

			getListNewAssessItem();

			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);

			TextView mNoData = (TextView) getView().findViewById(R.id.no_data);
			mNoData.setVisibility(TextView.GONE);
			ViewGroup mHasData = (ViewGroup) getView().findViewById(R.id.has_data);
			mHasData.setVisibility(ViewGroup.VISIBLE);
		}

	}

	private void saveAssessTranStep1() {
		// First Page Load
		saveAssessTran = new AssessTran();

		saveAssessTran.RESOURCE_ID = null;
		saveAssessTran.StationName = items.stationName;
		saveAssessTran.ProjectName = items.projectName;
		saveAssessTran.CycleName = items.cycle;

		saveAssessTran.YearAssessId = items.yearAssessId;
		saveAssessTran.StationId = items.stationId;
		saveAssessTran.AssessDate = new Date();
		saveAssessTran.CreateDate = new Date();
		saveAssessTran.ProjectId = items.projectId;
		saveAssessTran.CycleAssessId = items.cycleAssessId;
		saveAssessTran.Status = AppUtil.ASSESS_STATUS_NONE;
		saveAssessTran.UserId = login.Employee_ID;
		saveAssessTran.UserTypeId = login.User_Group_Code;

		saveAssessTran.PBL_ID = items.locationId;
		saveAssessTran.TotalPoint = 0;

		CycleAssess cycleAssess = getCycleAssess(items.cycleAssessId);
		if (cycleAssess != null) {
			saveAssessTran.CycleAssessStartMonth = cycleAssess.CycleAssessStartMonth;
			saveAssessTran.CycleAssessStartYear = cycleAssess.CycleAssessStartYear;
			saveAssessTran.CycleAssessEndMonth = cycleAssess.CycleAssessEndMonth;
			saveAssessTran.CycleAssessEndYear = cycleAssess.CycleAssessEndYear;
		}

		String containItem = "";
		int netTotal = 0;
		AssessItemChoice5018List itemChoiceList = new AssessItemChoice5018List();
		AssessSubject5019List subjectList = new AssessSubject5019List();
		for (AssessItem assessItem : items.assessItem) {
			if (!containItem.equals(assessItem.CycleAssessSubjectId) || containItem.length() == 0) {
				itemChoiceList = new AssessItemChoice5018List();
				AssessSubject5019 AessessSubject5019 = new AssessSubject5019();
				AessessSubject5019.AssessSubjectId = assessItem.AssessSubjectId;
				AessessSubject5019.CycleAssessSubjectPoint = assessItem.CycleAssessSubjectPoint;
				AessessSubject5019.TotalRawPoint = 0;
				AessessSubject5019.WeightPoint = Integer.parseInt(assessItem.CycleAssessSubjectPoint);
				AessessSubject5019.UserComment = AppUtil.EMPTY;
				AessessSubject5019.Items.add(itemChoiceList);

				subjectList.AssessSubject5019Map.put(assessItem.CycleAssessSubjectId, AessessSubject5019);

				// Add Summary from GetAssessTran
				if (containItem.length() != 0) {
					summaryAssess.get(containItem).netTotal = netTotal;
					subjectList.AssessSubject5019Map.get(containItem).TotalFullPoint = netTotal;
				}

				netTotal = 0;
				SummaryAssess mSummary = new SummaryAssess();
				mSummary.subjectId = assessItem.CycleAssessSubjectId;
				mSummary.subjectName = assessItem.AssessSubjectName;
				mSummary.subjectTotal = Integer.parseInt(assessItem.CycleAssessSubjectPoint);
				mSummary.sumTotal = 0;
				mSummary.percentTotal = 0;
				mSummary.weightTotal = 0;
				mSummary.UserComment = AppUtil.EMPTY;
				summaryAssess.put(mSummary.subjectId, mSummary);

				containItem = assessItem.CycleAssessSubjectId;
			}
			AssessItemChoice5018 AssessItemChoice5018 = new AssessItemChoice5018();
			AssessItemChoice5018.AssessItemId = assessItem.AssessItemId;
			AssessItemChoice5018.AssessItemName = assessItem.AssessItemName;
			AssessItemChoice5018.CycleAssessSubjectId = assessItem.CycleAssessSubjectId;
			AssessItemChoice5018.AssessSubjectName = assessItem.AssessSubjectName;
			AssessItemChoice5018.AssessSubjectId = assessItem.AssessSubjectId;
			AssessItemChoice5018.AssessChoiceId = AppUtil.EMPTY;
			AssessItemChoice5018.AssessChoicePoint = AppUtil.EMPTY;
			itemChoiceList.AssessItemChoiceMap.put(AssessItemChoice5018.AssessItemId, AssessItemChoice5018);

			netTotal += Integer.parseInt(assessItem.MaxPoint);
		}
		// Add Summary from GetAssessTran - Last Index
		summaryAssess.get(containItem).netTotal = netTotal;
		subjectList.AssessSubject5019Map.get(containItem).TotalFullPoint = netTotal;

		saveAssessTran.Subjects.add(subjectList);

		saveSummaryPref.saveMap(projCycleStationId, summaryAssess);
	}

	private CycleAssess getCycleAssess(String cycleAssessId) {
		// TODO Auto-generated method stub
		CycleAssess CycleAssess = null;
		for (CycleAssess aCycleAssess : search.cycles.CycleAssess) {
			if (aCycleAssess.CycleAssessId.equals(cycleAssessId)) {
				CycleAssess = aCycleAssess;
			}
		}

		return CycleAssess;
	}

	private void saveAssessTranStep2_saveGPSLocation(String GPSLocation) {
		saveAssessTran.GPSLocation = GPSLocation;
	}

	private void saveAssessTranStep2_saveUserComment(String subjectId, String UserComment) {
		AssessSubject5019 AessessSubject5019 = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(subjectId);
		SummaryAssess summary = summaryAssess.get(subjectId);
		summary.UserComment = UserComment;
		summaryAssess.put(subjectId, summary);
		AessessSubject5019.UserComment = UserComment;

	}

	private void saveAssessTranStep2_saveScore(String subjectId, String itemId, String pointId, String point, String pointName) {
		AssessItemChoice5018 AssessItemChoice5018 = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(subjectId).Items.get(0).AssessItemChoiceMap.get(itemId);
		AssessItemChoice5018.AssessChoiceId = pointId;
		AssessItemChoice5018.AssessChoicePoint = point;
		AssessItemChoice5018.AssessChoicePointName = pointName;

		AssessSubject5019 AessessSubject5019 = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(subjectId);
		SummaryAssess summary = summaryAssess.get(subjectId);
		AessessSubject5019.TotalFullPoint = summary.netTotal;
		AessessSubject5019.TotalRawPoint = summary.sumTotal;
		AessessSubject5019.WeightPoint = summary.subjectTotal;

	}

	private void saveAssessTranStep4_saveDraft() {
		saveAssessTran.Status = AppUtil.ASSESS_STATUS_DRAFT;
		int grandWeightTotal = 0;
		for (SummaryAssess summary : summaryAssess.values())
			if (summary.netTotal != 0)
				grandWeightTotal += summary.weightTotal;
		saveAssessTran.TotalPoint = grandWeightTotal;

		// First Page Load
		PropertyInfo projProp = new PropertyInfo();
		projProp.setName(AppUtil.ProjectId);
		projProp.setValue(items.projectId);
		projProp.setType(String.class);

		PropertyInfo cycleProp = new PropertyInfo();
		cycleProp.setName(AppUtil.CycleAssessId);
		cycleProp.setValue(items.cycleAssessId);
		cycleProp.setType(String.class);

		PropertyInfo ResourceProp = new PropertyInfo();
		ResourceProp.setName(AppUtil.UserTypeId);
		ResourceProp.setValue(login.User_Group_Code);
		ResourceProp.setType(String.class);

		PropertyInfo StationProp = new PropertyInfo();
		StationProp.setName(AppUtil.STATIONID);
		StationProp.setValue(items.stationId);
		StationProp.setType(String.class);

		mTask = new DefaultTask(com, getString(R.string.method_getassesstranlastupdate), Boolean.TRUE);
		mTask.delegate = this;
		mTask.execute(ResourceProp, projProp, cycleProp, StationProp);

	}

	private void UploadImage(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		SuggestionImage image = (SuggestionImage) objects[0];

		try {
			int serverResponseCode = Integer.parseInt((String) output);
			if (serverResponseCode == 200) {
				onDecrementCount();
			} else {
				Toast.makeText(getActivity(), getString(R.string.alert_save_image_failed), Toast.LENGTH_LONG).show();
				canBack = true;
				WidgetUtil.showProgress(mContentView, mProgressView, false);
			}

		} catch (Exception e) {
			Toast.makeText(getActivity(), getString(R.string.alert_save_image_failed), Toast.LENGTH_LONG).show();
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}

	}

	@Override
	public void setCount(int cnt) {
		// TODO Auto-generated method stub
		this.cnt = cnt;
	}

	@Override
	public void onDecrementCount() {
		// TODO Auto-generated method stub
		cnt--;
		if (cnt <= 0) {
			Log.i("saveAssessTranStep4_SaveDraft", "PASS");
			saveAssessTranStep4_saveDraft();
		}
	}

	@Override
	public void onDecrementCount(View view, int cnt) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDecrementCount(boolean flag) {
		// TODO Auto-generated method stub

	}

}
